<!DOCTYPE html>
	<html>
	<head>
		<title>放大镜效果</title>
		<meta charset="utf-8">
		<style type="text/css">
		body{position: relative;}
		*{margin: 0;padding:0;}
		#Box{
			height:300px; 
			width:300px;
			position: relative;
			border:1px solid gray;
		}
		#bigBox{
			height:300px; 
			width:300px;
			position: absolute;
			top:0;
			left:310px;
			overflow: hidden;
			display:none;
			border: 1px solid gray;
		}
		#Box img{
			height:300px; 
			width:300px;
			}
		#lay{
			background:#fff;
			border:1px solid gray;
			position: absolute;
			top:0;
			left: 0;
			opacity:0.5;
			display:none;
		}
		</style>
		<script type="text/javascript">
			window.onload = function(){
				var Box = document.getElementById("Box");
				var bigBox = document.getElementById("bigBox");
				var bigbox = getChildNodes(bigBox)[0];
				var lay = document.getElementById("lay");
				//鼠标移入时，将放大镜和bigBox显示出来
				Box.onmouseover = function(){
					lay.style.display = "block";
					bigBox.style.display = "block";
				}
				//鼠标移出时，将放大镜和bigBox隐藏起来
				Box.onmouseout = function(){
					lay.style.display = "none";
					bigBox.style.display = "none";
				}
				Box.onmousemove = function(e){
					var scale = 4;//图片的放缩比例
					//将鼠标放到放大镜的中间
					var x = e.clientX - lay.offsetWidth/2;
					var y = e.clientY - lay.offsetHeight/2;
					//将放大镜的宽高与盒子的宽高结合起来按比例放缩
					lay.style.width = parseInt(Box.offsetWidth / scale )+ "px";
					lay.style.height = parseInt(Box.offsetHeight / scale)+ "px";
					//设置大盒子的宽高
					bigbox.style.width = Box.offsetWidth * scale + "px";
					bigbox.style.height = Box.offsetHeight * scale + "px";
					if(x < 0){
						x = 0;//左边界的判断，当超出时将x置为0;
					}
					//右边界的判断，当超出时将x置为Box的宽度减去放大镜的宽度;
					if( x >= Box.offsetWidth - lay.offsetWidth){
						x = Box.offsetWidth - lay.offsetWidth;
					}
					//下边界的判断，当超出时将y置为Box的高度减去放大镜的高度;
					if( y >= Box.offsetHeight - lay.offsetHeight){
						y = Box.offsetHeight - lay.offsetHeight;
					}
					if(y < 0){
						y = 0;//上边界的判断，当超出时将y置为0;
					}
					lay.style.left = x + "px";
					lay.style.top = y + "px";
					//同比例放缩，大的盒子图片的放缩比例，当小盒子向右移动的时候，大盒子向左移动同等的比例的宽高，方向是相反的
					 var left = lay.offsetLeft * scale;
					 var top  = lay.offsetTop * scale ;
					bigbox.style.marginLeft =(left * (-1)) + "px";
					bigbox.style.marginTop =(top * (-1))+ "px";
 
					
				}
				
			}
			//获取孩子的节点
			function getChildNodes(element){
 				var arr = [];
	 			var eList = element.childNodes;
	 			for(var i = 0;i < eList.length;i++){
	 				if(eList[i].nodeType == 1){//过滤空白节点
	 					arr.push(eList[i]); 
	 				}
	 		     } 
	 		     return arr;
	 	    }
		</script>
		
	</head>
	<body>
		<div id="Box">
			<img  src="./img/img/1631931829165.jpg"/>
			<span id="lay"></span>
		</div>
		<div id="bigBox">
			<img  src="./img/img/1631931829165.jpg" />
		</div>
	</body>
	</html>